package Cantella::DJabberd::Web::UI::ViewPort::User::Auth;

use Reaction::Class;
use aliased 'Reaction::UI::ViewPort';
use aliased 'Reaction::UI::ViewPort::Action';
use aliased 'Cantella::DJabberd::Web::UI::ViewPort::User::Status';

extends ViewPort;

has auth_model =>
  (
   is   => 'ro',
   isa  => 'Reaction::InterfaceModel::Object',
   handles   => [qw/has_current_user current_user/],
   lazy_fail => 1,
  );

has login_form  => (is => 'ro', isa => ViewPort, lazy_build => 1);
has logout_form => (is => 'ro', isa => ViewPort, lazy_build => 1);

sub _build_login_form {
  my $self = shift;
  my $c = $self->ctx;

  Action->new(
              ctx     => $c,
              model    =>  $self->auth_model->action_for('Login', ctx => $c),
              location => join('-', $self->location, 'login'),
              apply_label => 'Log in',
              field_order => [qw/username password/],
              on_apply_callback => sub {
                $c->response->redirect($c->uri_for("/"));
                #figure something out $self->ctx->res->redirect();
              },
             );
}

sub _build_logout_form {
  my $self = shift;
  my $c = $self->ctx;

  Action->new(
              ctx   => $c,
              model =>  $self->auth_model->action_for('Logout', ctx => $c),
              location => join('-', $self->location, 'logout'),
              apply_label => 'Log out',
              on_apply_callback => sub {
                #figure something out $self->ctx->res->redirect();
              },
             );
}

override child_event_sinks => sub {
  my ($self) = @_;
  my $vp = $self->has_current_user ? $self->logout_form : $self->login_form;
  return ($vp, super());
};

__PACKAGE__->meta->make_immutable;

1;
